# -*- coding:utf8-*-
import http.cookiejar
import socket
import urllib.request
import urllib.parse
import urllib.error as error
from urllib.parse import urlparse, urlencode


# 请求
def request_demo_1():
    res = urllib.request.urlopen('http://www.baidu.com')
    print(res.read().decode('utf-8'))


def request_demo_2():
    data = bytes(urllib.parse.urlencode({'world': 'hello'}), encoding='utf-8')
    res = urllib.request.urlopen('http://httpbin.org/post', data=data)
    print(res.read())


def request_demo_3():
    try:
        res = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
    except urllib.error.URLError as e:
        if isinstance(e.reason, socket.timeout):
            print('TIME OUT')


def request_demo_4():
    res = urllib.request.urlopen('https://www.python.org')
    print(type(res))
    print(res.status)
    print(res.getheaders())
    print(res.getheader('Server'))


# 响应
def response_demo_1():
    req = urllib.request.Request('http://python.org')
    res = urllib.request.urlopen(req)
    print(res.read().decode('utf-8'))


def response_demo_2():
    url = 'http://httpbin.org/post'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        'Host': 'httpbin.org'
    }
    dict1 = {
        'name': 'wanghongfu'
    }
    data = bytes(urllib.parse.urlencode(dict1), encoding='utf-8')
    req = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
    # req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
    res = urllib.request.urlopen(req)
    print(res.read().decode('utf-8'))


# 代理

def proxy_handle_demo():
    proxy_hander = urllib.request.ProxyHandler({
        'http': 'http://127.0.0.1:9743',
        'https': 'https://127.0.0.1:9743'
    })
    opener = urllib.request.build_opener(proxy_hander)
    res = opener.open('https://www.baidu.com')
    print(res.read().decode('utf-8'))


# cookie

def cookie_demo_1():
    cookie = http.cookiejar.CookieJar()
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    res = opener.open('https://www.teambition.com/todo')
    for item in cookie:
        print(item.name + '=' + item.value)


def cookie_demo_2():
    file_name = 'cookie.txt'
    cookie = http.cookiejar.MozillaCookieJar(file_name)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    res = opener.open('https://www.teambition.com/todo')
    cookie.save(ignore_discard=True, ignore_expires=True)


def cookie_demo_3():
    file_name = 'cookie.txt'
    cookie = http.cookiejar.LWPCookieJar(file_name)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    res = opener.open('https://www.teambition.com/todo')
    cookie.save(ignore_discard=True, ignore_expires=True)


def cookie_demo_4():
    cookie = http.cookiejar.LWPCookieJar()
    cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    res = opener.open('https://www.teambition.com/todo')
    print(res.read().decode('utf-8'))


# 异常处理
def error_demo():
    try:
        res = urllib.request.urlopen("http:dsd/s/ddwe")
    except error.HTTPError as e:
        print(e.reason, e.code, e.headers, sep='\n')
    except error.URLError as e:
        print(e.reason)
    else:
        print('Request Successfully')


# url 解析
def url_parse_demo_1():
    result = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
    print(result)


#     urlunparse
# urljoin


# urlencode
def urlencode_demo():
    params = {
        'name': 'wanghongfu',
        'age': 29
    }
    base_url = 'http://www.baidu.com?'
    print(base_url + urlencode(params))


if __name__ == '__main__':
    # request_demo_1()
    # request_demo_2()
    # request_demo_3()
    # request_demo_4()
    # response_demo_1()
    # response_demo_2()
    # cookie_demo_1()
    # cookie_demo_2()
    # cookie_demo_3()
    # cookie_demo_4()
    # error_demo()
    # url_parse_demo_1()
    urlencode_demo()
